import  {socket} from './socket.js'
import {check_alarm,sleep,showNotification} from "./utils.js";
import {FIRE_CONFIDENCE_THRESHOLD,SMOKE_CONFIDENCE_THRESHOLD,MAX_FRAME_COUNT,PROPORTION_THRESHOLD} from "./alarmConfig.js"
// 文件上传
const imageUpload = document.getElementById('image-upload');
const videoUpload = document.getElementById('video-upload');
const uploadImageBtn = document.getElementById('upload-image-btn');
const uploadVideoBtn = document.getElementById('upload-video-btn');
const previewImage = document.getElementById('preview-image');
const previewVideo = document.getElementById('preview-video');
const saveResultBtn = document.getElementById('save-result-btn');
const progressContainer = document.getElementById('progress-container');
const alarmContainer = document.getElementById('alarm-container');

let current_file_name = '';
// 文件选择器选择后展示内容
imageUpload.addEventListener('change', (e) => {
    if (e.target.files && e.target.files[0]) {
        const reader = new FileReader();
        reader.onload = (e) => {
            previewImage.src = e.target.result;
            previewImage.classList.remove('hidden');
            previewVideo.classList.add('hidden');
            saveResultBtn.disabled = true;
        };
        reader.readAsDataURL(e.target.files[0]);
    }
});
// 同样展示
videoUpload.addEventListener('change', (e) => {
    if (e.target.files && e.target.files[0]) {
        const videoUrl = URL.createObjectURL(e.target.files[0]);
        previewVideo.src = videoUrl;
        previewVideo.classList.remove('hidden');
        previewImage.classList.add('hidden');
        saveResultBtn.disabled = true;
    }
});

uploadImageBtn.addEventListener('click', () => {
    // 禁用保存按钮，关闭摄像头，帧生成停止

    if (!imageUpload.files.length) {
        alert('请先选择图片');
        return;
    }
    const imageFile = imageUpload.files[0];
    const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!allowedImageTypes.includes(imageFile.type)) {
        alert("请上传 JPEG、PNG 或 GIF 格式的图片！");
        return;
    }
    const formData = new FormData();
    formData.append('image', imageFile);
    console.log(formData);
    console.log(imageFile);
    video_output_stop();
    stopDisplayFrames();
    fetch('/upload/image', {
        method: 'POST',
        body: formData
    })
   .then(response => response.blob())
   .then(blob => {
        const objectURL = URL.createObjectURL(blob);
        previewImage.src = objectURL;
        // 清空缓存区
        saveResultBtn.disabled = false;
        //enableSaveButton(); // 启用保存按钮
    })
   .catch(error => {
        console.error('上传图片失败:', error);
    });
    current_file_name = imageFile.name;
});

uploadVideoBtn.addEventListener('click', () => {
    if (!videoUpload.files.length) {
        alert('请先选择视频');
        return;
    }
    const videoFile = videoUpload.files[0];
    const allowedVideoTypes = ['video/mp4', 'video/avi', 'video/mov'];
    if (!allowedVideoTypes.includes(videoFile.type)) {
        alert("请上传 MP4、AVI 或 MOV 格式的视频！");
        return;
    }
    const formData = new FormData();
    formData.append('video', videoFile);
    alarmContainer.innerHTML = '';//清空报警信息
    video_output_stop();
    stopDisplayFrames();
    fetch('/upload/video', {
        method: 'POST',
        body: formData
    })
   .then(response => response.json())
   .then(data => {
        console.log(data);
        if('match' in data){
            // 直接取就好了。
            const formData = new FormData();
            formData.append('filename', data['filename']);
            //closeCamera();
            video_output_stop();
            fetch('/download/video', {
                method: 'POST',
                body: formData
            })
           .then(response => response.blob())
           .then(blob => {
                console.log("blob");
                console.log(blob);
                video_output_stop();
                stopDisplayFrames();
                const objectURL = URL.createObjectURL(blob);
                previewVideo.src = objectURL;
                previewVideo.controls = true;
                previewImage.classList.add('hidden');
                previewVideo.classList.remove('hidden');

                console.log("展示可下载视频");
                saveResultBtn.disabled = false;
                //enableSaveButton(); // 启用保存按钮
            })
           .catch(error => {
                console.error('上传视频失败:', error);
            });

        }else {
            socket.emit("process_and_show_video_frame", data['filename']);
        }
    })
   .catch(error => {
        console.error('上传视频失败:', error);
    });
    current_file_name = videoFile.name;
});


let recentFireConfidences = [];
let recentSmokeConfidences = [];
let frames = [];//缓冲区
let isLoading = false;
const bufferImage = new Image();
// 展示帧的函数
async function displayFrames(INTERVAL) {
    isLoading = true;
    while (frames.length > 0) {
        previewImage.classList.remove('hidden');
        previewVideo.classList.add('hidden');
        const url = frames.shift();
        bufferImage.onload = () => {
            previewImage.src = url;
            URL.revokeObjectURL(url); // 释放 URL 对象
        };
        bufferImage.src = url;
        await sleep(INTERVAL);
    }
    isLoading = false;
}
function stopDisplayFrames(){
    frames = [];
    isLoading = false;
}
socket.on("processed_video_frame", (data) => {
    const blob = new Blob([data['frame']], { type: 'image/jpeg' });
    const cls_conf = data['cls_conf'];
    //console.log(cls_conf);
    // 接下来就是分析conf，置信度
    const url = URL.createObjectURL(blob);
    frames.push(url);
    let INTERVAL = 1000/data['fps'];
    console.log('processed_video_frame',data,INTERVAL);
    const receiveTime = new Date();
    console.log('接收帧数据，时间：', receiveTime.toLocaleTimeString());
    if (frames.length >= 2*data['fps'] && !isLoading) {
        displayFrames(INTERVAL);
    }
     if(data['progress'] === -1){
        console.log("没有进度条信息!");
    }else{
        console.log("收到进度条信息！");
        var progress = (data["progress"] * 100).toFixed(2);
        var filename = data["filename"];
        createProgressBar(filename);
        changeProgress(filename,progress);
        if(data['progress'] === 1){
            console.log("视频处理完成，删除进度条。");
            sleep(5000);
            deleteProgressBar(filename);
            // 因为此时后台还不一定处理完文件了。
            //发送文件名到后端，然后展示
            const formData = new FormData();
            formData.append('filename', filename);
            fetch('/download/video', {
                method: 'POST',
                body: formData
            })
           .then(response => response.blob())
           .then(blob => {
                console.log("blob");
                console.log(blob);
                // 停止生成帧
                video_output_stop();
                // 必须停止播放帧，否则会导致缓冲区还有帧在展示，hidden顶替掉展示的视频
                stopDisplayFrames();

                //previewVideo;
                const objectURL = URL.createObjectURL(blob);
                previewVideo.src = objectURL;
                previewVideo.controls = true;
                previewImage.classList.add('hidden');
                previewVideo.classList.remove('hidden');
                console.log("展示可下载视频");
                saveResultBtn.disabled = false;
                //enableSaveButton(); // 启用保存按钮
            })
           .catch(error => {
                console.error('下载视频失败:', error);
            });
        }
    }
    // 处理置信度已决定是否报警
    const result = check_alarm(cls_conf,MAX_FRAME_COUNT,recentFireConfidences,recentSmokeConfidences,FIRE_CONFIDENCE_THRESHOLD,SMOKE_CONFIDENCE_THRESHOLD,PROPORTION_THRESHOLD);
    const now = new Date();
    const time = now.toLocaleTimeString();
    if (result.fire === 1) {
        //const newAlarm = `<div class="alarm-info fire">${time}: 火焰报警</div>`;
        const newAlarm = `<div class="p-3 bg-red-50 border-l-4 border-red-400 rounded-r-lg flex items-center">
            <i class="fa fa-exclamation-circle text-red-500 mr-2"></i>
            <span class="text-red-700">${time}:  检测到火焰</span>
        </div>`;

        alarmContainer.innerHTML += newAlarm;
        // 将滚动条滚动到最底部
        alarmContainer.scrollTop = alarmContainer.scrollHeight;
    }
    if (result.smoke === 1) {
        const newAlarm = `<div class="p-3 bg-yellow-50 border-l-4 border-yellow-400 rounded-r-lg flex items-center">
                        <i class="fa fa-exclamation-triangle text-yellow-500 mr-2"></i>
                        <span class="text-yellow-700">${time}: 检测到烟雾</span>
                    </div>`;
        alarmContainer.innerHTML += newAlarm;
        // 将滚动条滚动到最底部
        alarmContainer.scrollTop = alarmContainer.scrollHeight;
    }
});

async function video_output_stop(){
    console.log("发送中止视频帧生成信号");
    socket.emit("video_output_stop");
    clearProgressBarComponent();
}
socket.on('stop_video_output',(data) => {
    showNotification("中止即时视频帧输出！");
    console.log("中止即时视频帧输出");
})
// 保存结果按钮
saveResultBtn.addEventListener('click', () => {
    const isImageHidden = previewImage.classList.contains('hidden');
    const isVideoHidden = previewVideo.classList.contains('hidden');
    let element;
    if(isImageHidden&&!isVideoHidden){
        element = previewVideo;
    }else{
        element = previewImage;
    }
    //console.log(isImageHidden,isVideoHidden);
    console.log(current_file_name,element);
    const link = document.createElement('a');
    link.href = element.src;
    link.download = current_file_name;
    link.click();
});

function createProgressBar(fileName) {
    let progressDiv = findProgressBarComponent(fileName);
    if (progressDiv) {
        console.log(`进度条已存在: ${fileName}`);
        return progressDiv;
    }

    console.log(`创建进度条: ${fileName}`);
    progressDiv = document.createElement('div');
    progressDiv.id = `progress-${fileName}`; // 使用fileName作为ID
    progressDiv.className = 'progress-item mb-4';
    progressDiv.setAttribute('data-file', fileName); // 存储文件名数据

    const header = document.createElement('div');
    header.className = 'flex justify-between items-center mb-2';

    const nameSpan = document.createElement('span');
    nameSpan.className = 'text-sm font-medium text-gray-700';
    nameSpan.textContent = `${fileName}：`;

    const progressText = document.createElement('span');
    progressText.className = 'progress-text text-sm font-medium text-primary';
    progressText.textContent = '0%';

    const progressWrapper = document.createElement('div');
    progressWrapper.className = 'w-full bg-gray-200 rounded-full h-2.5';

    const progressBar = document.createElement('div');
    progressBar.className = 'progress-bar bg-primary h-2.5 rounded-full transition-all duration-300';
    progressBar.style.width = '0%';

    header.appendChild(nameSpan);
    header.appendChild(progressText);
    progressWrapper.appendChild(progressBar);
    progressDiv.appendChild(header);
    progressDiv.appendChild(progressWrapper);
    progressContainer.appendChild(progressDiv);

    return progressDiv;
}
function changeProgress(fileName, width) {
    const progressDiv = findProgressBarComponent(fileName);
    if (!progressDiv) {
        console.error(`未找到进度条: ${fileName}`);
        return;
    }

    width = Math.max(0, Math.min(100, width)); // 限制范围0-100%
    const progressBar = progressDiv.querySelector('.progress-bar');
    const progressText = progressDiv.querySelector('.progress-text');

    progressBar.style.width = `${width}%`;
    progressText.textContent = `${width}%`;
}

function deleteProgressBar(fileName) {
    const progressDiv = findProgressBarComponent(fileName);
    if (progressDiv) {
        progressDiv.remove();
        console.log(`删除进度条: ${fileName}`);
    } else {
        console.log(`未找到进度条: ${fileName}`);
    }
}

function findProgressBarComponent(fileName) {
    return document.getElementById(`progress-${fileName}`);
}
function clearProgressBarComponent(){
    progressContainer.innerHTML = '';
    console.log("清空进度条容器");
}